package com.github.shiqiyue.app.config.security.gapi;

import com.github.shiqiyue.app.common.utils.HttpServletRequestUtils;

import javax.servlet.http.HttpSession;

/***
 *
 * @author wenyao.wu
 * @since 2020/9/10
 */
public class GapiSecurityContext {

    private static final String SESSION_NAME = "GAPI_LOGIN_USER";

    private static ThreadLocal<GapiLoginUser> loginUserThreadLocal = new ThreadLocal<>();

    public static GapiLoginUser getCurrentLoginUser() {
        GapiLoginUser gapiLoginUser = loginUserThreadLocal.get();
        if (gapiLoginUser == null) {
            gapiLoginUser = getLoginInfo(HttpServletRequestUtils.getSession());
            if (gapiLoginUser != null) {
                set(gapiLoginUser);
            }
        }
        return loginUserThreadLocal.get();
    }

    public static void set(GapiLoginUser gapiLoginUser) {
        loginUserThreadLocal.set(gapiLoginUser);
    }

    public static void clear() {
        loginUserThreadLocal.remove();
    }

    /***
     * 登录
     * @param gapiLoginUser
     * @param httpSession
     */
    public static void login(GapiLoginUser gapiLoginUser, HttpSession httpSession) {
        httpSession.setAttribute(SESSION_NAME, gapiLoginUser);
    }

    /***
     * 登出
     * @param httpSession
     */
    public static void logout(HttpSession httpSession) {
        httpSession.invalidate();
    }

    /***
     * 获取登录信息
     * @param httpSession
     * @return
     */
    public static GapiLoginUser getLoginInfo(HttpSession httpSession) {
        return (GapiLoginUser) httpSession.getAttribute(SESSION_NAME);
    }
}
